package com.example.hosptial.service.impl;

import com.example.hosptial.model.enity.Patient;
import com.example.hosptial.repository.PatientRepository;
import com.example.hosptial.service.PatientService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true)  // 默认只读事务
public class PatientServiceImpl implements PatientService {

    private static final Logger logger = LoggerFactory.getLogger(PatientServiceImpl.class);

    @Autowired
    private PatientRepository patientRepository;

    @Override
    public List<Patient> getPatientsByDoctor(String doctorId) {
        if (doctorId == null || doctorId.trim().isEmpty()) {
            throw new IllegalArgumentException("医生ID不能为空");
        }
        logger.info("正在查询医生ID为 {} 的所有病人", doctorId);
        List<Patient> patients = patientRepository.findByDoctorDoctorId(doctorId);
        logger.info("找到 {} 个病人", patients.size());
        patients.forEach(patient -> 
            logger.debug("病人信息: ID={}, 姓名={}, 性别={}, 年龄={}", 
                patient.getPatientId(), 
                patient.getPatientName(),
                patient.getPatientGender(),
                patient.getPatientAge())
        );
        return patients;
    }

    @Override
    public List<Patient> searchPatientsByName(String doctorId, String patientName) {
        if (doctorId == null || doctorId.trim().isEmpty()) {
            throw new IllegalArgumentException("医生ID不能为空");
        }
        if (patientName == null || patientName.trim().isEmpty()) {
            throw new IllegalArgumentException("患者姓名不能为空");
        }
        logger.info("正在搜索医生ID为 {} 的病人，搜索关键词: {}", doctorId, patientName);
        List<Patient> patients = patientRepository.findByDoctorDoctorIdAndPatientNameContaining(doctorId, patientName.trim());
        logger.info("找到 {} 个匹配的病人", patients.size());
        return patients;
    }

    @Override
    public Map<String, Object> getPatientDetail(Integer patientId) {
        if (patientId == null || patientId <= 0) {
            throw new IllegalArgumentException("无效的患者ID");
        }
        logger.info("正在获取病人ID为 {} 的详细信息", patientId);
        Map<String, Object> details = patientRepository.getPatientDetails(patientId);
        logger.info("成功获取病人详情");
        return details;
    }
}